package it.polimi.traveldream;

import java.util.ArrayList;
import java.util.List;

import it.polimi.traveldream.entities.User;

import javax.annotation.Resource;
import javax.annotation.security.RolesAllowed;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class GestioneUtente implements GestioneUtenteLocal{
	
	@PersistenceContext
	private EntityManager em;
	
	@Resource
	private EJBContext context;

	@Override
	public void save(UtenteDTO client) {
		System.out.print("dentro metodo save");
		User nuovoUtente = new User(client);
		
		List<Group> groups = new ArrayList<Group>();
		groups.add(Group.USER);
		nuovoUtente.setGroups(groups);
		
		em.persist(nuovoUtente);
	  }

	@Override
	public void update(UtenteDTO user) {
		User utente=em.find(User.class,user.getEmail());
				
		utente.setCognome(user.getCognome());
		utente.setNome(user.getNome());
		
		System.out.print(utente.getEmail());
		System.out.print(utente.getPassword());
		System.out.print(utente.getDataregistrazione());
				
		List<Group> groups = new ArrayList<Group>();
		groups.add(Group.USER);
		utente.setGroups(groups);
		
		em.merge(utente);
		
	}

	@Override
	public void unregister() {
		// TODO Auto-generated method stub
		
	}

	
	@Override
	public UtenteDTO getUserDTO() {
		return null;
	}
	
	//--------------- ricerca utente by email ---------------
	
	@Override
	@RolesAllowed({Group._USER/*,Group._EMPLOYEE*/})
	public UtenteDTO findUserByEmail() {
		UtenteDTO userDTO = convertToDTO(getPrincipalUser());
		return userDTO;
	}
	
	
    private User find(String email) {
    	return em.find(User.class, email);
       }
	
	 private User getPrincipalUser() {
	    	return find(getPrincipalEmail());
	    }
		
	    
	 private String getPrincipalEmail() {
			return context.getCallerPrincipal().getName();
	    }
	    
	 private UtenteDTO convertToDTO(User user) {
			UtenteDTO userDTO = new UtenteDTO();
			userDTO.setEmail(user.getEmail());
			userDTO.setNome(user.getNome());
			userDTO.setCognome(user.getCognome());
			return userDTO;
		}
	 
	 //--------------------- fine ricerca ----------------------------------
	    
	/*@Override
	public UtenteDTO findUserByEmail(String email){
		return null;
	}*/
	
	
 }
